// UserDaoImpl.java
package com.community.dao.impl;
import com.community.dao.UserDao;
import com.community.model.User;
import com.community.util.DBUtil;
import java.sql.*;
import java.util.Optional;

public class UserDaoImpl implements UserDao {
    private static final String SELECT_BY_USERNAME = "SELECT * FROM users WHERE username=?";
    private static final String INSERT_SQL = "INSERT INTO " +
            "users(username,password,role) VALUES(?,?,?)";

    @Override
    public Optional<User> getByUsername(String username) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(SELECT_BY_USERNAME)) {
            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            return rs.next() ? Optional.of(mapRow(rs)) : Optional.empty();
        } catch (SQLException e) {
            throw new RuntimeException("Query failed", e);
        }
    }

    @Override
    public void insert(User user) {
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(INSERT_SQL)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getRole());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("Insert failed", e);
        }
    }

    @Override
    public void delete(int id) {

    }

    @Override
    public Optional<User> getById(int id) {
        return Optional.empty();
    }

    @Override
    public void update(User user) {

    }
//主要功能是把关系型数据库中的记录映射成 Java 对象
    private User mapRow(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setRole(rs.getString("role"));
        return user;
    }
}